package HTTP

import (
	"SQL/db"
	"logs"
	"net/http"
	"strconv"
)

/*URL:  /getGroupMember
群成员列表：
s groupID string,pageIndex int,pageSize int
r Message string,
  [MemberID string,MemberIcon string] */
type member struct {
	MemberID   string
	MemberIcon string
}

func getGroupMember(w http.ResponseWriter, req *http.Request) {
	msg, code := prepare(w, req)
	var obj interface{}
	defer func() {
		writeResult(w, code, msg, obj)
	}()
	if msg != "" {
		return
	}
	groupID, _ := strconv.Atoi(req.Form["groupID"][0])
	pageIndex, _ := strconv.Atoi(req.Form["pageIndex"][0])
	pageSize, _ := strconv.Atoi(req.Form["pageSize"][0])
	sql := "select *from groups where id =$1"
	rows, err := db.RowQuery(sql, groupID)
	defer rows.Close()
	if rows.Next() == false {
		msg = mNotExistGroupID
		code = errGroupIDNotExist
		return
	}
	sql = "select id,icon from objects,members where members.groupid = $1 and members.userid =objects.id order by id asc limit $2 offset $3"
	offset := pageIndex * pageSize
	var args []interface{}
	args = append(args, groupID, pageSize, offset)
	rows, err = db.RowQuery(sql, args...)
	defer rows.Close()
	if err != nil {
		logs.Print("GroupList Query error", err.Error())
		code = errDBQueryFailed
		msg = err.Error()
		return
	}
	members := make([]member, 0)
	var count int
	for rows.Next() {
		count++
		var memberid string
		var membericon string
		err = rows.Scan(&memberid, &membericon)
		if err != nil {
			logs.Print("GroupMember rows.Scan error", err.Error())
		}
		tem := &member{MemberID: memberid, MemberIcon: membericon}
		members = append(members, *tem)
	}
	if count == 0 {
		msg = "该页已经没有数据了"
		return
	}
	obj = members
	msg = "获取群成员成功"
}
